package com.excellent.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
public class FileController {

    @Value("${my.resource.dir}")
    private String resourceDir;


    @Value("${my.upload.dir}")
    private String uploadDir;


    //   接收上传的图片并用时间戳重命名文件，保留文件后缀，返回新的文件名和结果
    @PostMapping("/upload")
    public ResponseEntity<Map<String, String>> uploadImage(MultipartFile file) {
        // 创建一个Map来存储要返回给客户端的数据
        Map<String, String> responseData = new HashMap<>();
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成新的文件名，包含时间戳和原文件的后缀
        String newFileName = System.currentTimeMillis() + suffix;
        try {
//            File uploadDir = new File(uploadDir);
//            if (!uploadDir.exists()) {
//                if (!uploadDir.mkdirs()) {
//                    throw new IOException("无法创建上传目录");
//                }
//            }
            // 将上传的文件保存到服务器上的指定目录下
            file.transferTo(new File(uploadDir + newFileName));
            responseData.put("message", "success");
            responseData.put("fileName", newFileName);
            // 返回一个包含状态码和数据的ResponseEntity对象
            return new ResponseEntity<>(responseData, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            responseData.put("message", "eror");
            return new ResponseEntity<>(responseData, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
